package rsj.threadpool;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义线程池
 * @author yuanqinglong
 * @since 2020/11/23 10:50
 */
@Configuration
public class MyThreadExecutorPool implements AsyncConfigurer {


    @Bean
    public ThreadPoolTaskExecutor myThreadTaskAsyncPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 获取处理器核数
        int processors = Runtime.getRuntime().availableProcessors();
        // 设置核心线程数是处理器核数+1
        executor.setCorePoolSize(processors + 1);
        // 设置最大线程数是处理器核数两倍+1
        executor.setMaxPoolSize((processors << 1) + 1);
        // 阻塞队列最大容量
        executor.setQueueCapacity(500);
        executor.setKeepAliveSeconds(30);
        executor.setThreadNamePrefix("MyExecutor-");
        // 拒绝策略 使用默认策略直接抛出异常
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.initialize();
        return executor;
    }


    /**
     * 设置Spring的 @Async异步方法默认使用自定义线程池执行
     * @return 自定义线程池
     */
    @Override
    public Executor getAsyncExecutor() {
        return myThreadTaskAsyncPool();
    }
}
